<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog v-model="openFlag" :title="title" width="400" append-to-body>
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px" class="dialog-form-two">
        <el-row>
          <el-col :span="24">
            <el-form-item label="名称" prop="companyId">
              <company-select disabled :value="companyId"></company-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名称" prop="deptName">
              <el-input v-model.trim="formData.deptName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model.trim="formData.leader" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import api from "./api.js";
import { ref, reactive, computed, defineEmits, defineExpose } from 'vue';
import CompanySelect from "@/components/CommonSelect/CompanySelect.vue";

const { proxy } = getCurrentInstance();
const emit = defineEmits(['sub']);
const openFlag = ref(false);
const isEdit = ref(false);
const title = computed(() => isEdit.value ? '编辑' : '新增');

const companyId = inject('companyId')

const form = ref();
const formData = reactive({
  companyId: null,
  id: null,
  name: null,
  code: null,
  leader: null,
  address: null
});


const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" }
  ],
  leader: [
    { required: true, message: "负责人不能为空", trigger: "blur" }
  ],
};

function open(row) {
  Object.assign(formData, row);
  openFlag.value = true;
}

function close() {
  openFlag.value = false;
}

function submitForm() {
  form.value.validate(valid => {
    if (valid) {
      const params = { ...formData };
      params.companyId = companyId.value;
      if (isEdit.value) {
        api.update(params).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          close();
          emit("sub");
        });
      } else {
        api.add(params).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          close();
          emit("sub");
        });
      }
    }
  });
}

defineExpose({
  open
});
</script>